package cn.byzk.xframe.web.session.annotations;

import cn.byzk.xframe.web.session.util.SessionUtil;
import cn.byzk.xframe.web.session.TokenMemory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class ToLogoutTokenAspect {

    @Autowired
    private TokenMemory tokenMemory;

    /**
     * 定义切入点
     * @author xcf
     * @date 2021/5/6 9:20
     * @param toLogoutToken
     */
    @Pointcut(value = "@annotation(toLogoutToken)", argNames = "toLogoutToken")
    public void pointcut(ToLogoutToken toLogoutToken) {

    }


    /**
     * return前进行处理,Token
     * @author xcf
     * @date 2021/5/6 12:18
     * @param joinPoint
     * @param userObj
     */
    @AfterReturning(value = "@annotation(cn.byzk.xframe.web.session.annotations.ToLogoutToken)", returning = "userObj")
    public void afterReturning(JoinPoint joinPoint, Object userObj) {

        String token = SessionUtil.getToken();
        tokenMemory.remove(token);

        //SessionUtil.removeToken(token);
        SessionUtil.removeAllSession();
    }

    /**
     * 退出时出现异常也清空session, Token
     * @author xcf
     * @date 2021/5/6 12:19
     * @param joinPoint
     * @param ex
     */
    @AfterThrowing(value = "@annotation(cn.byzk.xframe.web.session.annotations.ToLogoutToken)", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Throwable ex) {

        String token = SessionUtil.getToken();
        tokenMemory.remove(token);
        SessionUtil.removeAllSession();
    }
}
